<?php

	// Copied from PHP Docs to disable Magic Quotes
	if (get_magic_quotes_gpc()) {
		$process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
		while (list($key, $val) = each($process)) {
			foreach ($val as $k => $v) {
				unset($process[$key][$k]);
				if (is_array($v)) {
					$process[$key][stripslashes($k)] = $v;
					$process[] = &$process[$key][stripslashes($k)];
				} else {
					$process[$key][stripslashes($k)] = stripslashes($v);
				}
			}
		}
		unset($process);
	}

	$_REQUEST['fileSettings'] = str_replace("\\\\", "\\", $_REQUEST['fileSettings']);
	$fileSettings = json_decode($_REQUEST['fileSettings'], true);	
	$tmpFilename = uniqid();

	switch($_REQUEST['type']) {
		case 'dwca':
			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Content-Type: application/zip");
			header("Content-Disposition: inline; filename=" . $tmpFilename . ".zip");
			header("Content-Transfer-Encoding: binary");

			$fp = fopen("tmp/" . $tmpFilename . ".csv", 'w');
#			fputs($fp, "\xEF\xBB\xBF");
			$list = json_decode($_REQUEST['list'], true);
			foreach ($list as $row) {
				$line = array(
						$row["orig"]
					, $row["scientificName"]
					, $row["source"]
					, $row["comment"]
					,	$row["taxonID"]
					, $row["kingdom"]
					, $row["phylum"]
					, $row["class"]
					, $row["order"]
					, $row["family"]
					, $row["genus"]
					,	$row["isSynonym"]
					,	$row["acceptedName"]
					,	$row["accordingTo"]
				);
				fputcsv($fp, $line);
			}
			fclose($fp);

			$info = json_decode($_REQUEST['info'], true);
			$eml = file_get_contents("eml_tpl.xml");
			$find = array("{AUTHOR}", "{TITLE}", "{PUBLISHER}", "{DATE}", "{SOURCE}", "{ISSN}", "{DOI}", "{ISBN}", "{SICI}");
			$rpl = array($info["author"], $info["title"], $info["publisher"], $info["date"], $info["url"], $info["issn"], $info["doi"], $info["isbn"], $info["sici"]);
			$eml = str_replace($find, $rpl, $eml);
			$fp = fopen("tmp/" . $tmpFilename . ".eml", 'w');
			fwrite($fp, $eml);
			fclose($fp);

			$zip = new ZipArchive;
			if ($zip->open("tmp/" . $tmpFilename . ".zip", ZipArchive::CREATE) === TRUE) {
				$zip->addFile("meta.xml", "meta.xml");
				$zip->addFile("tmp/" . $tmpFilename . ".csv", "records.csv");
				$zip->addFile("tmp/" . $tmpFilename . ".eml", "dc.xml");
				$zip->close();
				@unlink("tmp/" . $tmpFilename . ".csv");
				@unlink("tmp/" . $tmpFilename . ".eml");
				$fp = fopen("tmp/" . $tmpFilename . ".zip", 'rb');
				fpassthru($fp);
			}
			break;
		
		case 'txt':
			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Content-Type: application/txt");
			header("Content-Disposition: inline; filename=" . $tmpFilename . ".txt");
			header("Content-Transfer-Encoding: binary");
			$list = explode("<br>", $_REQUEST['list']);
			print implode("\r\n", $list);
			break;
			
		case 'csv':
			$list = json_decode($_REQUEST['list'], true);
			
			$header = array("Original Name", "Scientific Name", "Found By"
				, "Comments", "GBIF Ref. ID", "Kingdom", "Phylum"
				, "Class", "Order", "Family", "Genus", "Synonym", "Accepted Name Usage", "Name According To"
			);
			$fileExt = ($fileSettings["Field Delimiter"] == ",") ? ".csv" : ".txt";

			header("Pragma: public");
			header("Expires: 0");
			header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
			header("Content-Type: application/csv");
			header("Content-Disposition: inline; filename=" . $tmpFilename . $fileExt);
			header("Content-Transfer-Encoding: binary");

			if (!$fileSettings["Ignore header row"]) {
				print implode($fileSettings["Field Delimiter"], $header) . $fileSettings["Line ending"];
			}
#			print_r($list);
			foreach($list as $row) {
				$line = array(
						$row["orig"]
					, $row["scientificName"]
					, $row["source"]
					, $row["comment"]
					,	$row["taxonID"]
					, $row["kingdom"]
					, $row["phylum"]
					, $row["class_"]
					, $row["order"]
					, $row["family"]
					, $row["genus"]
					,	$row["isSynonym"]
					,	$row["acceptedName"]
					,	$row["accordingTo"]
				);

				print $fileSettings["Fields enclosed by"] . implode($fileSettings["Fields enclosed by"] . $fileSettings["Field Delimiter"] . $fileSettings["Fields enclosed by"], $line) . $fileSettings["Fields enclosed by"] . $fileSettings["Line ending"];
			}
			break;	
	}
?>